
package com.jt.zcdemo;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.ColorScheme;
import com.microsoft.playwright.options.Cookie;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

public class Bbbb2 {
    private final static String SHIPINHAO_SPIDER_HOME_URL = "https://channels.weixin.qq.com/platform";
    private final static String SHIPINHAO_SPIDER_LIVE_URL = "https://channels.weixin.qq.com/platform/live/home";

    private static Map<String, String> buildEnvMap() {
        Map<String, String> map = new HashMap<>();
        map.put("PLAYWRIGHT_BROWSERS_PATH", "C:\\pw-browsers\\ms-playwright");
        return map;
    }

    private static void setCookies(BrowserContext browserContext, String cookies) {
        String[] cookieArray = cookies.split(";");
        List<Cookie> cookieList = new ArrayList<>();
        for (String cookie : cookieArray) {
            String[] pair = cookie.split("=", 2);
            if (pair.length == 2) {
                cookieList.add(new Cookie(pair[0].trim(), pair[1].trim())
                        .setDomain("channels.weixin.qq.com")
                        .setPath("/"));
            }
        }
        browserContext.addCookies(cookieList);
    }

    // 封装 shadow DOM 按钮查找
    private static String getShadowBtnScript() {
        return "() => { " +
                "let root = document;" +
                "['wujie-app', 'div.container-center'].forEach(selector => {" +
                "  root = root.querySelector(selector)?.shadowRoot || root;" +
                "});" +
                "const btn = root.querySelector('button.weui-desktop-btn.weui-desktop-btn_primary:not(.weui-desktop-btn_mini)');" +
                "return btn && btn.offsetParent !== null;" +
                "}";
    }

    public static String getVideoUrl(String cookies) {
        AtomicReference<String> normalUrl = new AtomicReference<>("");
        try (Playwright playwright = Playwright.create(new Playwright.CreateOptions().setEnv(buildEnvMap()))) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext(new Browser.NewContextOptions().setColorScheme(ColorScheme.DARK));
            Page page = context.newPage();
            page.navigate(SHIPINHAO_SPIDER_LIVE_URL);
            setCookies(context, cookies);

            page.navigate(SHIPINHAO_SPIDER_HOME_URL);
            page.waitForTimeout(5000);

            // 点击[直播]菜单
            page.waitForSelector("#menuBar > li:nth-child(4) > a");
            page.locator("#menuBar > li:nth-child(4) > a").click();

            // 点击[直播管理]子菜单
            page.waitForSelector("#menuBar > li:nth-child(4) > ul > li:nth-child(1)");
            Locator liveManage = page.locator("#menuBar > li:nth-child(4) > ul > li:nth-child(1)");
            if (liveManage.isVisible()) {
                System.out.println("元素位置：" + liveManage.boundingBox());
            } else {
                System.out.println("元素不可见");
            }
            liveManage.click();

            // 监听网络响应
            page.onResponse(response -> {
                if (response.url().contains("join_live")) {
                    String responseBody = response.text();
                    JsonObject jsonObject = new Gson().fromJson(responseBody, JsonObject.class);
                    JsonObject liveInfo = jsonObject.getAsJsonObject("data")
                            .getAsJsonObject("liveInfo");
                    String streamUrl = liveInfo.get("streamUrl").getAsString();
                    normalUrl.set(streamUrl);
                }
            });

            // 等待 shadow DOM 按钮可见
            page.waitForTimeout(5000);
            Object btnVisibleObj = page.evaluate(getShadowBtnScript());
            boolean btnVisible = btnVisibleObj instanceof Boolean && (Boolean) btnVisibleObj;
            if (btnVisible) {
                // 进入直播间
                page.evaluate("() => { " +
                        "let root = document;" +
                        "['wujie-app', 'div.container-center'].forEach(selector => {" +
                        "  root = root.querySelector(selector)?.shadowRoot || root;" +
                        "});" +
                        "const btn = root.querySelector('button.weui-desktop-btn.weui-desktop-btn_primary:not(.weui-desktop-btn_mini)');" +
                        "if (btn) btn.click();" +
                        "}");
                page.waitForTimeout(5000);
            } else {
                System.out.println("未开播");
            }
            if (!normalUrl.get().isEmpty()) {
                return normalUrl.get().replace("&amp;", "&").replaceAll("&quot;|\"", "");
            }
        } catch (Exception e) {
            System.err.println("获取视频源地址异常: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Map<String, Object> result = new HashMap<>(4);
        String cookies = "sessionid=BgAAIfwttFFnYvO5ITd%2BDub6aTzODuA4ZXy%2BnU1JNXMI7l4%2BTIitEa0Yx7i3EE5siUb%2BBT33RH8R%2FufSMXyzkKDmh0MV1fEZVASqNx9MrmUo; other_cookie=value;";
        String normalUrl = getVideoUrl(cookies);
        System.out.println("获取到视频源地址11111111：" + normalUrl);
        result.put("normalUrl", normalUrl);
    }
}